package com.syp.envops.controller;

import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.syp.envops.domain.vo.ConfigVo;
import com.syp.envops.domain.vo.UploadVo;
import com.syp.envops.service.ConfigServiceI;
import com.syp.envops.util.Constants;
import com.syp.envops.util.ProcessResult;
import com.syp.envops.util.sftp.SftpFile;

@Controller
@RequestMapping("/config")
public class ConfigController {

	private static final Logger logger = LoggerFactory.getLogger(ConfigController.class);

	@Autowired
	private ConfigServiceI configService;

	@RequestMapping("/list.tpl")
	public String listTpl() {
		return "config/list";
	}

	@ResponseBody
	@RequestMapping("/list")
	public ProcessResult list(Integer sid, String path, Integer plevel) {
		ProcessResult pr = new ProcessResult();
		try {
			plevel = plevel == null ? plevel = 0 : plevel;
			List<SftpFile> fileList = configService.list(sid, path, Constants.RECURSIVE_LIST_FILE);
			List<ConfigVo> configList = configService.transform(fileList, plevel);
			pr.setSuccess(true);
			pr.setMessage("配置列表查询成功。");
			pr.getRet().put("configList", configList);

		} catch (Exception e) {
			logger.error("配置列表查询失败:", e);

			pr.setSuccess(false);
			pr.setMessage("配置列表查询失败。");
		}
		return pr;
	}

	@RequestMapping("/view.tpl")
	public String viewTpl() {
		return "config/view";
	}

	@RequestMapping("/edit.tpl")
	public String editTpl() {
		return "config/edit";
	}

	@RequestMapping("/info.dialog")
	public String infoDialog() {
		return "config/info.dialog";
	}

	@RequestMapping("/content")
	@ResponseBody
	public ProcessResult content(@RequestBody ConfigVo config) {
		ProcessResult pr = new ProcessResult();
		try {
			SftpFile sftpFile = configService.get(config.getServerId(), config.getAbsolutePath());
			pr.setSuccess(true);
			pr.setMessage("获取配置文件内容成功。");
			pr.getRet().put("config", sftpFile);

		} catch (Exception e) {
			logger.error("获取配置文件内容失败:", e);

			pr.setSuccess(false);
			pr.setMessage("获取配置文件内容失败。");
		}
		return pr;
	}

	@RequestMapping("/edit")
	@ResponseBody
	public ProcessResult edit(@RequestBody SftpFile sf) {
		ProcessResult pr = new ProcessResult();
		try {
			configService.save(sf.getServerId(), sf.getAbsolutePath(), sf.getContent().getBytes(Constants.CHARSET_UTF8));
			pr.setSuccess(true);
			pr.setMessage("编辑配置文件内容成功。");
			pr.getRet().put("config", sf);

		} catch (Exception e) {
			logger.error("编辑配置文件内容失败:", e);

			pr.setSuccess(false);
			pr.setMessage("编辑配置文件内容失败。");
		}
		return pr;
	}

	@RequestMapping("/edit.result.tpl")
	public String editResultTpl() {
		return "config/edit.result";
	}

	@RequestMapping("/add.dialog")
	public String addTpl() {
		return "config/add.dialog";
	}

	@RequestMapping("ddel")
	@ResponseBody
	public ProcessResult ddel(@RequestBody ConfigVo config) {
		ProcessResult pr = new ProcessResult();
		try {
			System.out.println("serverId: " + config.getServerId());
			System.out.println("path: " + config.getAbsolutePath());
			System.out.println("isDir:" + config.getIsDir());
			configService.rm(config.getServerId(), config.getAbsolutePath(), config.getIsDir());
			pr.setSuccess(true);
			pr.setMessage("删除配置成功。");
		} catch (Exception e) {
			logger.error("删除配置失败:", e);
			pr.setSuccess(false);
			pr.setMessage("删除配置失败。");
		}
		return pr;
	}

	@RequestMapping("addDir")
	@ResponseBody
	public ProcessResult addDir(@RequestBody UploadVo uploadVo) {
		ProcessResult pr = new ProcessResult();
		try {
			configService.mkDir(uploadVo.getServerId(), uploadVo.getConfigPath() + "/" + uploadVo.getConfigName());
			pr.setSuccess(true);
			pr.setMessage("创建目录成功。");
		} catch (Exception e) {
			logger.error("创建目录失败:", e);
			pr.setSuccess(false);
			pr.setMessage("创建目录失败。");
		}
		return pr;
	}

	@RequestMapping("addFile")
	@ResponseBody
	public ProcessResult addFile(HttpServletRequest request) {
		ProcessResult pr = new ProcessResult();
		try {
			Integer serverId = Integer.parseInt(request.getParameter("serverId"));
			String dirPath = request.getParameter("configPath");
			// 创建一个通用的多部分解析器
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
			// 判断 request 是否有文件上传,即多部分请求
			if (multipartResolver.isMultipart(request)) {
				// 转换成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 取得request中的所有文件名
				Iterator<String> iter = multiRequest.getFileNames();
				while (iter.hasNext()) {
					// 取得上传文件
					MultipartFile file = multiRequest.getFile(iter.next());
					if (file != null) {
						configService.uploadFile(serverId, dirPath, file);
					}
				}
			}
			pr.setSuccess(true);
			pr.setMessage("文件上传成功。");
		} catch (Exception e) {
			logger.error("文件上传失败:", e);
			pr.setSuccess(false);
			pr.setMessage("文件上传失败。");
		}
		return pr;
	}

}
